import vue from '@vitejs/plugin-vue';
import { defineConfig, loadEnv } from 'vite';
//用于vue、vue-router等自动导入
import AutoImport from 'unplugin-auto-import/vite';
//用于Vue3 setup 语法糖下定义组件名称
import vueSetupExtend from 'vite-plugin-vue-setup-extend';
//用于gzip压缩
import viteCompression from 'vite-plugin-compression';
// 打包分析
import { visualizer } from 'rollup-plugin-visualizer';
//用于设置@/的路径
import { resolve } from 'path';
const pathResolve = (dir) => {
	return resolve(__dirname, '.', dir);
};
const alias = {
	'@': pathResolve('./src/'),
};

const viteConfig = defineConfig((mode) => {
	const env = loadEnv(mode.mode, process.cwd());
	return {
		// 配置线上环境路径（打包）、本地通过 http-server 访问时，请置空即可
		// base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
		base: './',
		// 设置@/的路径
		resolve: { alias },
		plugins: [
			vue(),
			// setup自定义组件名称
			vueSetupExtend(),
			//自动引入ref等api
			AutoImport({
				imports: ['vue', 'vue-router'],
			}),
			//压缩
			viteCompression({
				verbose: true,
				disable: false,
				threshold: 10240,
				algorithm: 'gzip',
				ext: '.gz',
			}),
			// 打包分析
			visualizer({ open: true, brotliSize: true, filename: 'report.html' }),
		],
		root: process.cwd(),
		server: {
			host: '0.0.0.0',
			port: env.VITE_PORT,
			open: env.VITE_OPEN,
			// 反向代理
			proxy: {
				'/admin': {
					target: 'http://192.168.1.79',
					ws: true,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/admin/, '/admin'),
				},
			},
		},
		build: {
			minify: 'terser', //压缩方式
			outDir: 'dist', //打包文件夹名
			sourcemap: false, //清除map
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				output: {
					entryFileNames: `assets/[name].${new Date().getTime()}.js`,
					chunkFileNames: `assets/[name].${new Date().getTime()}.js`,
					assetFileNames: `assets/[name].${new Date().getTime()}.[ext]`,
					compact: true,
					manualChunks: {
						vue: ['vue', 'vue-router', 'pinia'],
						echarts: ['echarts'],
					},
				},
			},
			terserOptions: {
				compress: {
					drop_console: true, //清除console
					drop_debugger: true, //清除debugger
				},
				// ie8: true,
				output: {
					comments: true,
				},
			},
		},
		css: {
			postcss: {
				plugins: [
					{
						postcssPlugin: 'internal:charset-removal',
						AtRule: {
							charset: (atRule) => {
								if (atRule.name === 'charset') {
									atRule.remove();
								}
							},
						},
					},
				],
			},
		},
	};
});

export default viteConfig;
